//
//  CHInformViewController.m
//  CarFile
//
//  Created by 陈浩 on 2017/8/2.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHInformViewController.h"
#import "CHAnnounceViewController.h"
#import "CHInformDetailController.h"
#import "CHMenuView.h"
#import "CHNoticeModel.h"
#import "CHInformCell.h"
#import "CHContentScrollView.h"
@interface CHInformViewController ()<CHMenuViewDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) CHMenuView *menuView;
@property (nonatomic ,strong) CHContentScrollView *mainScrollView;
@property (nonatomic ,strong) UITableView *tzTableView;
@property (nonatomic ,strong) UITableView *fbTableView;
@property (nonatomic ,strong) NSMutableArray *noticeDatas;
@property (nonatomic ,strong) NSMutableArray *fbDatas;
@property (nonatomic ,strong) UIButton *addBtn;

@property (nonatomic ,assign) int index;
@property (nonatomic ,assign) BOOL isLoad;
@end

@implementation CHInformViewController
-(NSMutableArray *)fbDatas{
    if (!_fbDatas) {
        _fbDatas = [NSMutableArray array];
    }
    return _fbDatas;
}
-(NSMutableArray *)noticeDatas{
    if (!_noticeDatas) {
        _noticeDatas = [NSMutableArray array];
    }
    return _noticeDatas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"通知";
    self.view.backgroundColor = [UIColor whiteColor];
    _isLoad = NO;

    
    [self setupRightBarButtonItem];
    
    [self setupTitleMenu];
    
    [self setupMainScrollView];
    
    
    
}

-(void)setupRightBarButtonItem{
    
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.bounds = CGRectMake(0, 0, 40 ,15);
    addBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    addBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addBtn setTitle:@"发布" forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.addBtn = addBtn;
    self.addBtn.hidden = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    
}


-(void)addBtnClick{

    id obj = [LongriseRouter openURL:@"CHAnnounceViewController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

-(void)setupTitleMenu{
    
    NSArray *titles = @[@"上级通知",@"本区发布"];
    CHMenuView *menuView =[[ CHMenuView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, 44) withTitles:titles];
    menuView.delegate = self;
    menuView.isUnderline = NO;
    menuView.bgColor = [UIColor colorWithHexString:@"eeeef0" alpha:1.0f];
    [self.view addSubview:menuView];
    self.menuView = menuView;
    
}

-(void)setupMainScrollView{
    
    CHContentScrollView *mainScrollview = [[CHContentScrollView alloc] initWithFrame:CGRectMake(0,  CGRectGetMaxY(self.menuView.frame), UIScreenW, UIScreenH - CGRectGetMaxY(self.menuView.frame) -64)];
    mainScrollview.delegate = self;
    mainScrollview.pagingEnabled = YES;
    mainScrollview.scrollEnabled = YES;
    mainScrollview.bounces = NO;
    mainScrollview.showsHorizontalScrollIndicator = NO;
    mainScrollview.showsVerticalScrollIndicator = NO;
    //    mainScrollview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:mainScrollview];
    self.tzTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, mainScrollview.h)];
    self.tzTableView.backgroundColor = [UIColor colorWithHexString:@"111111" alpha:0.1f];
    self.tzTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tzTableView.delegate = self;
    self.tzTableView.dataSource = self;
    // 下拉刷新
    self.tzTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        
        [self getTZData];
    }];
//    self.tzTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        
////        [self loadMoreNoCheckData];
//    }];
    self.tzTableView.mj_footer.automaticallyHidden = YES;
    [mainScrollview addSubview:self.tzTableView];
    [self.tzTableView.mj_header beginRefreshing];
    

    
    self.fbTableView = [[UITableView alloc] initWithFrame:CGRectMake(UIScreenW, 0, UIScreenW, mainScrollview.h)];
    self.fbTableView.backgroundColor = [UIColor colorWithHexString:@"111111" alpha:0.1f];
    // 下拉刷新
    self.fbTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.fbTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        
        [self getFBDatas];
        
    }];
    self.fbTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreFBDatas];
    }];
    self.fbTableView.mj_footer.automaticallyHidden = YES;
    self.fbTableView.delegate = self;
    self.fbTableView.dataSource = self;
    [mainScrollview addSubview:self.fbTableView];
    
    mainScrollview.contentSize = CGSizeMake(UIScreenW *2, 0);
    self.mainScrollView = mainScrollview;
}




//   上级通知
-(void)getTZData{
    _index = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    params[@"type"] = @"2";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        [self.noticeDatas removeAllObjects];
//        NSLog(@"上级通知%@",result);
        [self.tzTableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.noticeDatas addObject:model];
            }
        
        }
        self.tzTableView.placeholderImage = @"data_null";
        self.tzTableView.placeholder = @"暂时没有数据哦~";
        [self.tzTableView reloadData];
    }];
}


//   本区发布
-(void)getFBDatas{
    _index = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    params[@"type"] = @"3";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        [self.fbDatas removeAllObjects];
  
        [self.fbTableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.fbDatas addObject:model];
            }
           
        }
        self.fbTableView.placeholderImage = @"data_null";
        self.fbTableView.placeholder = @"暂时没有数据哦~";
        [self.fbTableView reloadData];
    }];
}


-(void)loadMoreFBDatas{
    
    _index++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    params[@"type"] = @"3";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        [self.fbTableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.fbDatas addObject:model];
            }
            [self.fbTableView reloadData];
        }
    }];
}

//   删除
-(void)deleteDataWithNewsID:(NSString *)newsID{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:newsID encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"newsid"] = newsID;

    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewsdelete" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        [self.fbTableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            
        }else{
            
            
        }
    }];
    
}


#pragma mark - CHMenuViewDelegate
-(void)CHMenuView:(CHMenuView *)menuView didBtnClickWithTag:(NSInteger)tag{
    if (tag == 101) {
        self.addBtn.hidden = NO;
        if (!_isLoad) {
            [self.fbTableView.mj_header beginRefreshing];
            _isLoad = YES;
        }
    }else{
        self.addBtn.hidden = YES;
    }
    [self.mainScrollView setContentOffset:CGPointMake(( tag - 100) *UIScreenW, 0) animated:YES];

}


#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == self.mainScrollView) {
        
        int tag = (int)scrollView.contentOffset.x/self.view.size.width +100 ;
        
        UIButton *btn = (UIButton *)[self.menuView viewWithTag:tag];
        
        
        [self.menuView titleBtnClick:btn];
    }
    
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tzTableView) {
        return 0;
    }
    return self.fbDatas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tzTableView) {
        CHInformCell *cell = [CHInformCell cellForTableView:tableView];
        cell.model = self.noticeDatas[indexPath.row];
        return cell;
    }
    CHInformCell *cell = [CHInformCell cellForTableView:tableView];
    cell.model = self.fbDatas[indexPath.row];
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 120;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    id obj = [LongriseRouter openURL:@"CHInformDetailController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    //判断该类是否可以传参数
    if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
    {
        id<LongriseRouterDelegater> delegater = obj;
        if(delegater)
        {
            
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"model"] = self.fbDatas[indexPath.row];
            
            //进行传值，传入统一的block以供B进行回调
            [delegater setParams:params block:^(id obj) {
                
                
            }];
        }
    }
    
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
         CHNoticeModel *model = self.fbDatas[indexPath.row];
        
        
        // 删除数据源的数据,self.cellData是你自己的数据
        [self.fbDatas removeObjectAtIndex:indexPath.row];
        
        [self deleteDataWithNewsID:model.newsid];
        
        // 删除列表中数据
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
      
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";//默认文字为 Delete
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//
//补全分割线
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell  respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
    {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self.navigationController setNavigationBarHidden:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getFBDatas) name:@"sendSuccessMessage" object:nil];
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}



@end
